import {EventEmitter} from "events";
import {Client} from "./Client";
import {AbstractRoom} from "./room/AbstractRoom";
import {RoomFactory} from "./room/RoomFactory";

export class MatchManager<T extends AbstractRoom> extends EventEmitter {
  private queue: Client[] = [];
  private matchCount = 2;

  constructor(private roomClazz: { new(): T }) {
    super();
  }

  public listenMatch(client: Client) {
    client.on('match', this.onMatch.bind(this))
  }

  private onMatch(e: { data: any, target: Client }) {
    console.log('onmatch')
    this.queue.push(e.target);
    if (this.queue.length >= this.matchCount) {
      this.onMatchSuccess();
    }
  }

  private onMatchSuccess() {
    const room = RoomFactory.generator(this.roomClazz);
    const data = [];
    for (let i = 0; i < this.matchCount; i++) {
      const client = this.queue.shift();
      console.log(client.sessionId);
      (room as any)._join(client)
      data.push(client.user);
    }
    console.log(data)
    room.broadcast('matchSuc', data);
    room.start();
  }

  static matchRoom<T extends AbstractRoom>(roomClazz: { new(): T }): MatchManager<T> {
    return new MatchManager(roomClazz);
  }
}